package com.cmz.common.utils;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author cmz
 * @date 2020/2/27 14:02
 */
public class SystemClockUtils {
    private static final String THREAD_NAME = "System.Clock";

    private static final SystemClockUtils MILLIS_CLOCK = new SystemClockUtils(1);

    private final long period;

    private final AtomicLong now;

    private SystemClockUtils(long period) {
        this.period = period;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern(THREAD_NAME).daemon(true).build());
        scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
    }

    public static long now() {
        return MILLIS_CLOCK.now.get();
    }
}
